# -*- coding: utf-8 -*-
# created on 2017/02/17

# 067.函数性质综合求函数解析式 - 不用自动推理

from sympy import sympify, simplify
from mathsolver.functions.base import BaseFunction, BaseFunc
from mathsolver.functions.hanshu.jiou_dingyi import jiou_dingyi
from mathsolver.functions.hanshu.zhouqi import has_f
from mathsolver.functions.sympy_utils import get_all_child
from mathsolver.functions.hanshu.helper import get_symmetric_interval


class ZhouQiJiOuQiuJieXiShi(BaseFunction):
    """已知函数周期性、奇偶性求解析式"""
    def solver(self, *args):
        # 处理输入
        zt, jiou, belong, func, interval = args
        zt = zt.sympify()
        belong_var, belong_interval = belong.var, belong.interval
        func_expr, func_var = func.expression, func.var

        # 奇偶定义式
        jiou_eq, jiou_step = jiou_dingyi(jiou)

        # x ∈ interval, 求出 -x ∈ symmetric_interval
        symmetric_interval = get_symmetric_interval(interval)
        self.steps.append(["", "由 x ∈ %s 得 -x ∈ %s " % (interval, symmetric_interval)])

        # -x ∈ symmetric_interval，求出 -x + n*T ∈ belong_interval
        left_val, right_val = symmetric_interval.args[:2]
        left_val0, right_val0 = belong_interval.args[:2]

        # 区间转换
        n = (left_val0 - left_val) / zt
        assert right_val + n * zt == right_val0
        self.steps.append(["", "所以 -x + %s ∈ %s" % (n * zt, belong_interval)])

        # 代入求值
        jiou_eq_left, jiou_eq_right = jiou_eq.args
        eq_inference = jiou_eq_right.subs(sympify('-x'), sympify("-x + %s * %s" % (n, zt)))

        f = get_all_child(eq_inference, has_f)[0]
        f_new = func_expr.subs(func_var, f.args[0])
        res = simplify(eq_inference.subs(f, f_new))

        step = str(jiou_eq_left) + " = " + str(jiou_eq_right) + " = " + str(eq_inference) + " = " + str(res)

        self.steps.append(["", "根据给定周期性和奇偶性可知"])
        self.steps.append(["", step])
        self.output.append(BaseFunc({'name': 'f', 'type': '', 'var': 'x', 'expression': res}))
        self.label.add("函数性质综合求函数解析式")
        return self


if __name__ == '__main__':
    pass
